import maya.cmds as mc

import motionMacht_facial.mouth_build.motionMacht_mouth_temple
reload(motionMacht_facial.mouth_build.motionMacht_mouth_temple)

import motionMacht_facial.head_stretch_build.head_stretcj_setting
reload(motionMacht_facial.head_stretch_build.head_stretcj_setting)

import LZ_public_command.LZ_UI
reload(LZ_public_command.LZ_UI)

import motionMacht_facial.eyeBrow_build.eyeBrown_builder
reload(motionMacht_facial.eyeBrow_build.eyeBrown_builder)

import motionMacht_facial.nose_build.motionMacht_nose_setting_builde
reload(motionMacht_facial.nose_build.motionMacht_nose_setting_builde)

import motionMacht_facial.eye_setting.motionMacht_createEyeSetting
reload(motionMacht_facial.eye_setting.motionMacht_createEyeSetting)

import motionMacht_facial.singgle_setting_build.motionMacht_singgle_setting_build
reload(motionMacht_facial.singgle_setting_build.motionMacht_singgle_setting_build)


import motionMacht_facial.eyeBrow_build.eyeBrown_builder as eyeBrown_builder
reload(eyeBrown_builder)

import LZ_public_command.LZ_Attribute as LZ_Attribute
reload(LZ_Attribute) 

class matchMotion_Edit_UI(motionMacht_facial.mouth_build.motionMacht_mouth_temple.mouth_temple_build,
                    LZ_public_command.LZ_UI.LZ_UI,
                    motionMacht_facial.head_stretch_build.head_stretcj_setting.head_stretch_setting,
                    motionMacht_facial.eyeBrow_build.eyeBrown_builder.eyeBrwon_builder,
                    motionMacht_facial.nose_build.motionMacht_nose_setting_builde.nose_setting_build,
                    motionMacht_facial.eye_setting.motionMacht_createEyeSetting.createEyeSetting,
                    motionMacht_facial.singgle_setting_build.motionMacht_singgle_setting_build.singgle_setting_build,
                    eyeBrown_builder.eyeBrwon_builder,
                    LZ_Attribute.LZ_attribute
                    ):

    def __init__(self):
    
        pass
        
        
    def matchMotion_Edit_UI(self):

        matchMotion_Edit_UI = 'matchMotion_Edit_UI'
        if mc.window(matchMotion_Edit_UI,ex = True):
            mc.deleteUI(matchMotion_Edit_UI)
            
        mc.window(matchMotion_Edit_UI,widthHeight=(400, 250),t='matchMotion_Edit_UI_v1.01_2015/07/20',menuBar = True,rtf=True,s=True)
        mc.columnLayout('main_layout',columnAttach=('both', 1), rowSpacing=10, columnWidth=400 )
        
        mc.columnLayout('ObjLoad_collayout',columnAttach=('both', 1), rowSpacing=10, columnWidth=390 )
        mc.rowLayout('ObjLoad_rowLY',numberOfColumns=2, columnWidth2=(120,350), adjustableColumn=2, columnAlign=(1, 'right'), columnAttach=[(1, 'both', 0), (2, 'both', 0)] )
        
        mc.button('bridge_matchInfo',c=lambda *args:self.loadObj2List01())
        mc.textField('ObjSelLoadTF',ed=False , text = 'infoMatch_bridge')
        #mc.text('-->>')
        #mc.textField('blenshapeName',ed=False)
        
        mc.setParent('main_layout')
        mc.rowLayout('blendList_rowLY',numberOfColumns=2, columnWidth2=(160, 240), adjustableColumn=2, columnAlign=(1, 'right'), columnAttach=[(1, 'both', 0), (2, 'both', 0)] )
        
        mc.textScrollList('bridge_attr_TSL',allowMultiSelection=True, height =  155,width = 95,sc=lambda *args:self.show_info_current()) #,dcc=lambda *args:self.selectConnectedObj()
        
        
        #mc.popupMenu(mm=True)
        #mc.menuItem('AppendTarget_menu',l ="Append",rp= "N",c=lambda *args:self.AppendTarget())
        #mc.menuItem('RemoveTarget_menu',l= "Remove",rp ="S",c=lambda *args:self.RemoveTarget())
        #mc.menuItem( 'ReplaceTarget_menu',l="Replace",rp ="W",c= lambda *args:self.ReplaceTarget())
        #mc.menuItem('RenameTarget_menu',l= "Rename",rp ="E",c=lambda *args:self.renameTargetWin())
        #mc.menuItem('ReBuild_Target_menu',l= "ReBuild_Target",rp ="NE",c=lambda *args:self.Rebuild_Target())
        #mc.menuItem('normalize_Target_menu',l= "normalize_Target",rp ="NW",c=lambda *args:self.normalize_Target())

        
        
        mc.textScrollList('SDK_object_TSL',allowMultiSelection=True, height =  155,width = 95,dcc=lambda *args:self.selectSDKObj(),sc=lambda *args:self.selectSDKObj())
        mc.popupMenu(mm=True)
        mc.menuItem('AppendTarget_menu',l ="Append",rp= "N",c=lambda *args:self.AppendTarget())
        mc.menuItem('RemoveTarget_menu',l= "Remove",rp ="S",c=lambda *args:self.RemoveTarget())
        mc.menuItem( 'ReplaceTarget_menu',l="reset",rp ="W",c= lambda *args:self.reset_daflut_value())
        #mc.menuItem('RenameTarget_menu',l= "Rename",rp ="E",c=lambda *args:self.renameTargetWin())
        #mc.menuItem('ReBuild_Target_menu',l= "ReBuild_Target",rp ="NE",c=lambda *args:self.Rebuild_Target())
        #mc.menuItem('normalize_Target_menu',l= "normalize_Target",rp ="NW",c=lambda *args:self.normalize_Target())
        
        
        
        
        
        #mc.columnLayout('blendshapeMenage_layout',columnAttach=('both', 1), rowSpacing=10, columnWidth=150 )
        #
        #mc.text('->> blend_Batch_menage <<-')
        #mc.button('Got_BlendShapeTarget',h=30)
        #mc.button('normalize_BlendShapeName',h=30,c=lambda *args:self.normalize_Target_All())
        #mc.button('select_All_Target',h=30,c=lambda *args:self.select_All_Target())
        
        mc.setParent('main_layout')
        
        mc.columnLayout('currentBlendWeightList_layout',columnAttach=('both', 1), rowSpacing=10, columnWidth=390 )
        mc.button('modify current motionShape',h=30,c=lambda *args:self.modify_current_motionShape())
        
        mc.rowLayout('info_translate_rowLY',numberOfColumns=4, columnWidth4=(60,120,60,120), adjustableColumn=4, columnAlign=(1, 'right'), columnAttach=[(1, 'both', 0), (2, 'both', 0), (3, 'both', 0), (4, 'both', 0)] )
        
        mc.button( 'loadMotion_Bs',l= 'M_bs',c = lambda *args:self.loadTextField(tfName = 'loadMotion_Bs_tf') )
        mc.textField('loadMotion_Bs_tf',w=120,ed=False)
        
        mc.button( 'loadMotion_bridge',l='M_bridge',c = lambda *args:self.loadTextField(tfName = 'loadMotion_bridge_tf') )
        mc.textField('loadMotion_bridge_tf',w=120,ed=False)
        
        
        mc.setParent('currentBlendWeightList_layout')
        mc.button('match_motion',h=30,c = lambda *args:self.match_motion_def())
        
        mc.button(' back animation ',h=30,c=lambda *args:self.back_squence_animation())
        mc.button('replace connection Window ',h=30,c=lambda *args:self.LZ_WrapDeformer_UI())
        
        self.load_bridge_info()
        if mc.objExists('infoMatch_value_bridge') == 1:
            mc.textField('loadMotion_bridge_tf',e=True, text = 'infoMatch_value_bridge')
        
        mc.window(matchMotion_Edit_UI,e=True,widthHeight=(400, 360))
        mc.showWindow()
    
    def match_motion_def(self):
        
        motion_source_info  =  mc.textField('loadMotion_Bs_tf',q = True,text = True )
        motion_target_info  =  mc.textField('loadMotion_bridge_tf',q = True,text = True )
        
        target = self.listAllTarget( blendShape_node = motion_source_info )
        for tg in target:
            source_connection = mc.listConnections( str(motion_source_info)+'.'+str(tg) , s=True , c=False ,p = True )
            
            if source_connection:
                mc.connectAttr( source_connection[0] , str(motion_target_info)+'.'+str(tg) )
            
        

    
    def AppendTarget(self):
        for i in mc.ls(sl=True) :
            
            allItem = mc.textScrollList('SDK_object_TSL',q=True, allItems = True )
            
            if allItem != None :
                if i not in allItem:
                     
                    mc.textScrollList('SDK_object_TSL',e=True ,append = i )
            else:
                mc.textScrollList('SDK_object_TSL',e=True ,append = i )
    def RemoveTarget(self):
        
            
        selectItem = mc.textScrollList('SDK_object_TSL',q=True, si = True )
            
        for i in selectItem :
        

            mc.textScrollList('SDK_object_TSL',e=True ,ri = i )

        
    def load_bridge_info(self):
        text_Bridge = mc.textField('ObjSelLoadTF',q=True, text = True)

        attr_Bridge = mc.listAttr( text_Bridge , userDefined =True)  
        mc.textScrollList('bridge_attr_TSL',e =True , ra = True )  

        for att in attr_Bridge:
            mc.textScrollList('bridge_attr_TSL',e =True , append = att )
        
    def show_info_current(self):
        text_Bridge = mc.textField('ObjSelLoadTF',q=True, text = True)
        Item = mc.textScrollList('bridge_attr_TSL',q =True , selectItem = True )[0]
        
        info = mc.getAttr(str(text_Bridge) + '.' +str(Item)   )
        
        
        mc.textScrollList('SDK_object_TSL',e=True, ra = True )
        split_path = str(info).split('@')
        
        for sp in split_path:
            contance = str(sp).split('#')
            if contance[0] == '':
                pass
            else:
                allItem = mc.textScrollList('SDK_object_TSL',q=True, allItems = True )
                if allItem != None :
                
                    if contance[0] not in allItem:
                        mc.textScrollList('SDK_object_TSL',e=True, append = contance[0] )
                else:
                    mc.textScrollList('SDK_object_TSL',e=True, append = contance[0] )

        self.set_current_value(  attr_string = str(text_Bridge) + '.' +str(Item)  , value_percent = 1.0  )
    def selectSDKObj(self):
        
        Item = mc.textScrollList('SDK_object_TSL',q =True , selectItem = True )
        mc.select( Item )
        
    def modify_current_motionShape(self):
    
        text_Bridge = mc.textField('ObjSelLoadTF',q=True, text = True)
        Item = mc.textScrollList('bridge_attr_TSL',q =True , selectItem = True )[0]
        
        SDKItem = mc.textScrollList('SDK_object_TSL',q =True , allItems = True )
        #print(len(SDKItem))
        match_info = ''
        for num in range(len(SDKItem)) :
            all_key_attr = mc.listAttr( str(SDKItem[num]) , k =True ,unlocked = True )
            
            infoAttr = str(SDKItem[num])
            for aka in all_key_attr:
                value = mc.getAttr(  str(SDKItem[num]) + '.'+str(aka)  ) 
                infoAttr = infoAttr + '#' + str(aka)+'#'+str(value)
            
                #print([  str(SDKItem[num]) + '.'+str(aka) , value])
            match_info = match_info + '@' + infoAttr
        #print(match_info)
        print(match_info)
        self.addStringAttr( obj = text_Bridge , attrName = Item , textinput = match_info , edit = 1 )
        
    
    def reset_daflut_value(self):
    
        object = mc.textField('ObjSelLoadTF',q=True , text = True )
        attribute = Item = mc.textScrollList('bridge_attr_TSL',q =True , selectItem = True )[0]
        
        self.reset_value( attr_string = str(object) + '.' +str(attribute)  )
    
    ###-----------------------------------
    
    def back_Animation(self, aniBridge = 'infoMatch_bridge' , time = [ 1,100] , framestep = 1  ):
        
        attr_Bridge = mc.listAttr( text_Bridge , userDefined =True)
        
        
        obj_sdk = []
        for attr in attr_Bridge:
            
            attribute = str(attr_Bridge)+'.' +str(attr)
            all_sdk_ojbj = self.list_all_SDK_objInfo( attr_string = attribute  )
            
            for aso in all_sdk_ojbj:
                
                if aso[0] not in obj_sdk:
                    
                    obj_sdk.append(aso[0])
        
        
        for i in range(  time[0] , time[1] , framestep ):
            for attr in attr_Bridge:
                pass
        
        mc.setKeyframe('ac_cn_lowlip_ctrl' , hierarchy ='none' ,shape =False)
            
            
        #reset_value

    def list_all_SDK_objInfo(self , attr_string = 'xxx.ttt'  ):
        
        value = mc.getAttr( attr_string )
        objSplit = str(value).split('@')
        #mc.getAttr()
        
        SDK_obj = []
        
        sdk_objs_info = []
        
        for obs in objSplit:
            
            allSplits = str(obs).split('#')
            obj = allSplits[0]
            
            #print( float(len(allSplits)))
            if (float(len(allSplits))-1.0)%2.0 == 0.0:
            
                atts_info = []
                for num in range((len(allSplits) - 1)/2 ):
                    
                    attr_num = num*2+1
                    attr = allSplits[ attr_num ]
                    
                    value_num = num*2+2
                    value = float(allSplits[ value_num ])
                    
                    atts_info.append( (attr , value ) )
            
            sdk_objs_info.append( [ obj , atts_info ])
        return sdk_objs_info
    
    def reset_value(self , attr_string = 'xxx.ttt'  ):
        
        value = mc.getAttr( attr_string )
        objSplit = str(value).split('@')
        #mc.getAttr()
        
        SDK_obj = []
        
        for obs in objSplit:
            
            allSplits = str(obs).split('#')
            obj = allSplits[0]
            #print( float(len(allSplits)))
            if (float(len(allSplits))-1.0)%2.0 == 0.0:
                for num in range((len(allSplits) - 1)/2 ):
                    
                    attr_num = num*2+1
                    attr = allSplits[ attr_num ]
                    
                    value_num = num*2+2
                    value = float(allSplits[ value_num ])
                    
                    daf_value = self.find_defluatValue(  obj  = obj  ,attr = attr )
                    
                    mc.setAttr( str(obj) + '.' + str(attr)  , daf_value  )
            
            
    def  set_current_value(self , attr_string = 'xxx.ttt' , value_percent = 1.0  ):
        
        
        value = mc.getAttr( attr_string )
        objSplit = str(value).split('@')
        #mc.getAttr()
        
        SDK_obj = []
        
        for obs in objSplit:
            
            allSplits = str(obs).split('#')
            obj = allSplits[0]
            #print( float(len(allSplits)))
            if (float(len(allSplits))-1.0)%2.0 == 0.0:
                for num in range((len(allSplits) - 1)/2 ):
                    
                    attr_num = num*2+1
                    attr = allSplits[ attr_num ]
                    
                    value_num = num*2+2
                    value = float(allSplits[ value_num ])
                    
                    daf_value = self.find_defluatValue(  obj  = obj  ,attr = attr )
                    value_act = (value - daf_value) * value_percent + daf_value
                    
                    
                    
                    min_max = self.list_minMax_attrValue( obj = obj ,attr = attr )
                    
                    ###-------------------------------------
                    #@print(min_max)
                    #@if min_max[1] != False:
                    #@
                    #@    if value_act >= min_max[1]:
                    #@        
                    #@        mc.setAttr( str(obj) + '.' + str(attr)  , min_max[1] )
                    #@        print( ( str(obj) + '.' + str(attr) ,3,min_max[1]) )
                    #@    else:
                    #@        if min_max[0] != False:
                    #@
                    #@            if value_act <= min_max[0]:
                    #@            
                    #@                mc.setAttr( str(obj) + '.' + str(attr)  , min_max[0] )
                    #@                print( ( str(obj) + '.' + str(attr) ,1,min_max[0]) )
                    #@            else:
                    #@            
                    #@                mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                    #@                print( ( str(obj) + '.' + str(attr) ,2,value_act ) )
                    #@        else:
                    #@
                    #@            mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                    #@        
                    #@else:
                    #@
                    #@
                    #@    print(2)
                    #@    if min_max[0] != False:
                    #@        
                    #@        if value_act <= min_max[0]:
                    #@        
                    #@            mc.setAttr( str(obj) + '.' + str(attr)  , min_max[0] )
                    #@        
                    #@        else:
                    #@            print( ( str(obj) + '.' + str(attr) ,2,value_act ) )
                    #@            mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                    #@            
                    #@    else:
                    #@        
                    #@        mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                    #@        print( ( 'hahahahah',str(obj) + '.' + str(attr) ,2,value_act ) )
                    #@
                    
                    
                    if min_max[1] != False:
                        if value_act >= min_max[1]:
                            
                            mc.setAttr( str(obj) + '.' + str(attr)  , min_max[1] )
                            
                        else:
                            if min_max[0] != False:
                            
                                if value_act <= min_max[0]:
                                
                                    mc.setAttr( str(obj) + '.' + str(attr)  , min_max[0] )
                                    
                                else:
                                
                                    mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                                    
                            else:

                                mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                                
                            
                    else:
                        
                        if min_max[0] != False:
                            
                            if value_act <= min_max[0]:
                            
                                mc.setAttr( str(obj) + '.' + str(attr)  , min_max[0] )
                                
                            
                            else:
                            
                                mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                                
                                
                        else:
                            
                            mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                            
                        
                    
                    
                    #---------------------------
                    
                    
                    #@if value_act >= min_max[1]:
                    #@
                    #@    mc.setAttr( str(obj) + '.' + str(attr)  , min_max[1] )
                    #@
                    #@elif value_act <= min_max[0]:
                    #@
                    #@    mc.setAttr( str(obj) + '.' + str(attr)  , min_max[0] )
                    #@
                    #@else:
                    #@
                    #@    mc.setAttr( str(obj) + '.' + str(attr)  , value_act )
                    #@

                        
        
    
    def grow_value(self, growth_attr = 'aaa.xxx' , value = 1 ):
        
        splits = str(growth_attr).split('.')
        dv_value = self.find_defluatValue(  obj  = splits[0]  ,attr = splits[1] )
        
        diff_value = value - dv_value
                
        return diff_value
    



    ##==================================================================================
    
    def back_squence_animation(self):
        
        startTime = 0
        endTime = 100
        bridge_grp = mc.textField('ObjSelLoadTF',q=True , text = True )
        for i in range(startTime,endTime):
        
            mc.currentTime(i)
            
            self.reset_all(  bridge = bridge_grp  )
            all_ctrlss = self.back_squence_keyframe(  bridge = bridge_grp  )
            
            for ac in all_ctrlss:
                if mc.objExists(ac) == True:
                    mc.setKeyframe(ac)
        

    
    def back_squence_keyframe( self , bridge = 'infoMatch_bridge' ,value_bridge = 'infoMatch_value_bridge'   ):
        
        attr_Bridge = mc.listAttr( bridge , userDefined =True) 
        

        
        all_ctrls = []
        for ab in attr_Bridge:
        
            attr_string = str(bridge)+'.' + str(ab)
            
            value_attr = mc.getAttr(str(value_bridge)+'.' + str(ab))
    
            value = mc.getAttr( attr_string )
            objSplit = str(value).split('@')
            #mc.getAttr()
            
            SDK_obj = []
            
            for obs in objSplit:
                
                allSplits = str(obs).split('#')
                obj = allSplits[0]
                
                if obj not in all_ctrls:
                    if obj != ' ':
                        all_ctrls.append(obj)
                
                #print( float(len(allSplits)))
                if (float(len(allSplits))-1.0)%2.0 == 0.0:
                    for num in range((len(allSplits) - 1)/2 ):
                        
                        attr_num = num*2+1
                        attr = allSplits[ attr_num ]
                        
                        value_num = num*2+2
                        value = float(allSplits[ value_num ])
                        
                        growth_value = self.grow_value(  growth_attr = str(obj)+'.'+str(attr) , value = value ) * value_attr
                        
                        currentValue = mc.getAttr( str(obj)+'.'+str(attr) )
                        
                        complexValue = currentValue + growth_value
                        
                        min_max = self.list_minMax_attrValue( obj = obj ,attr = attr )
                        
                        
                        if min_max[1] != False:
                            if complexValue >= min_max[1]:
                                
                                mc.setAttr( str(obj) + '.' + str(attr)  , min_max[1] )
                        
                            else:
                                if min_max[0] != False:
                                
                                    if complexValue <= min_max[0]:
                                    
                                        mc.setAttr( str(obj) + '.' + str(attr)  , min_max[0] )
                                    
                                    else:
                                    
                                        mc.setAttr( str(obj) + '.' + str(attr)  , complexValue )
                                else:

                                    mc.setAttr( str(obj) + '.' + str(attr)  , complexValue )
                                
                        else:
                            
                            if min_max[0] != False:
                                
                                if complexValue <= min_max[0]:
                                
                                    mc.setAttr( str(obj) + '.' + str(attr)  , min_max[0] )
                                
                                else:
                                
                                    mc.setAttr( str(obj) + '.' + str(attr)  , complexValue )
                                    
                            else:
                                
                                mc.setAttr( str(obj) + '.' + str(attr)  , complexValue )
                                
                                
                        #daf_value = self.find_defluatValue(  obj  = obj  ,attr = attr )
                        
                        #mc.setAttr( str(obj) + '.' + str(attr)  , daf_value  )
                        
        return all_ctrls
    def reset_all( self ,  bridge = 'infoMatch_bridge'   ):
        
        attr_Bridge = mc.listAttr( bridge , userDefined =True) 
        
        
        
        for ab in attr_Bridge:
            attr_string = str(bridge)+'.' + str(ab)
            
            print(attr_string)
            self.reset_value( attr_string = attr_string )   
    
    
    
        
    
        
    